<!-- components/charts/BaseChart.vue -->
<template>
  <div class="base-chart-container">
    <div v-if="isEmptyData" class="empty-chart">
      <el-empty description="暂无数据" :image-size="100">
      </el-empty>
    </div>
    <div v-else ref="chartRef" :style="{ height: height, width: width }"></div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  options: {
    type: Object,
    required: true
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  theme: {
    type: String,
    default: ''
  },
  // 新增：是否显示空状态
  showEmpty: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['chartReady', 'refresh'])

const chartRef = ref(null)
let chart = null

// 检查是否为空数据
const isEmptyData = computed(() => {
  if (!props.showEmpty) return false

  const options = props.options
  // 检查系列数据是否为空
  if (!options.series || options.series.length === 0) return true

  // 检查每个系列的数据是否为空
  return options.series.every(series => {
    if (!series.data || series.data.length === 0) return true
    // 检查数据是否都是0或空值
    return series.data.every(item => item === 0 || item === null || item === undefined)
  })
})

const initChart = () => {
  if (!chartRef.value || isEmptyData.value) return

  if (chart) {
    chart.dispose()
  }

  chart = echarts.init(chartRef.value, props.theme)
  chart.setOption(props.options, true)
  emit('chartReady', chart)
}

const resizeChart = () => {
  if (chart && !isEmptyData.value) {
    chart.resize()
  }
}

watch(() => props.options, () => {
  if (chart && !isEmptyData.value) {
    chart.setOption(props.options, true)
  }
}, { deep: true })

watch(isEmptyData, (newVal) => {
  if (newVal && chart) {
    // 如果变为空数据，销毁图表
    chart.dispose()
    chart = null
  } else if (!newVal && !chart) {
    // 如果从空数据变为有数据，重新初始化
    nextTick(() => {
      initChart()
    })
  }
})

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style scoped>
.base-chart-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.empty-chart {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #fafafa;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
}
</style>